#/usr/bin/perl -w

use strict;
use DBI;

my $filename = $ARGV[0];
my $tissue_type = $ARGV[1];

# ---------------------------------
# This part reads the db-settings.
# ---------------------------------

my $db_config_path = "../Perl/db_settings.txt";

#### Open input file
open DB_FILE, "<$db_config_path"
	or die "Something's wrong with the db config file!\n";

my $db_line = <DB_FILE>;		# holds the current line from the input file
my @db_conf_arr = split(/\s+/, $db_line);
my $username = shift @db_conf_arr;
my $password = shift @db_conf_arr;
my $database = shift @db_conf_arr;

close DB_FILE
        or die "Problem closing db-config file.\n";

# ----------------------------------------
# End reading db-settings.
# ----------------------------------------

### Create a connection to the database
my $dbh = DBI->connect(
    		"DBI:mysql:$database:localhost:3306",
    		$username,
    		$password
);


### Prepare the insertion statments which will later be executed in the write_to_db subfunction.
### The prepare_cached means that the handle is cached by the database and does not need to be
### recompiled each time it is called.

my $insert_handle_name_sym = $dbh->prepare_cached('INSERT INTO gene_names_symbols VALUES(?,?,?)')
               			or die "Couldn't prepare statement: " . $dbh->errstr;

#### Open input file
open INPUT_FILE, "<$filename"
	or die "Something's wrong with the input file!\n";

#-------------------------------------------------------------------------------
# Load the first row, which contains the individuals. Only chomp
#-------------------------------------------------------------------------------

my $line = <INPUT_FILE>;		# holds the current line from the input file
chomp $line;


#-------------------------------------------------------------------------------
# Start reading rows and filling the db-tables.
#-------------------------------------------------------------------------------
$line = <INPUT_FILE>;
my @row;					# array that will hold the current row of the file.
while (defined $line){
	chomp $line;
	@row = split(/\t/, $line);
	
	foreach (@row){
	s/\"//g;
	}

	my $probe_id = shift(@row);	
	my $gene_sym = shift(@row);	
	my $gene_name = shift(@row);
	my $count = 0;

		$insert_handle_name_sym->execute($probe_id, $gene_sym, $gene_name)
			or die "Couldn't execute insert statment to gene_names_symbols.";

		$count++;
	

	$line = <INPUT_FILE>;
}
$dbh->disconnect();


